﻿using System;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Ink;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using System.Windows.Browser;

namespace Twilight.ViewModels
{
    public class FloatingViewModel : RotatingViewModel
    {
        private HtmlElement plugin;
        private HtmlElement host;
        private Size defaultSize;
        private Size expandedSize;

        public FloatingViewModel()
        {
            LoadData();
        }

        protected override void LoadData()
        {
            base.LoadData();

            if (!IsDesignTime())
            {
                plugin = HtmlPage.Plugin;
                host = plugin.Parent;

                var position = GetHostPosition();

                host.SetStyleAttribute("position", "absolute");
                host.SetStyleAttribute("top", string.Format("{0}px", position.Y));
                host.SetStyleAttribute("left", string.Format("{0}px", position.X));
                host.SetStyleAttribute("z-index", "100000");

                //var width = plugin.GetAttribute("width");
                var height = int.Parse(host.GetStyleAttribute("height").Replace("px",""));

                //defaultSize = new Size(int.Parse(width), int.Parse(height));
                //expandedSize = new Size(defaultSize.Height + 100, defaultSize.Width);

                host.SetStyleAttribute("height", string.Format("{0}px", height + 100));   

            }
        }

        private Point GetHostPosition()
        {
            var id = host.GetAttribute("id");
            var position = HtmlPage.Window.Eval("function getPos() {var e = document.getElementById('" + id + "');var position = {X:0,Y:0};while (e){position.X += e.offsetLeft;position.Y += e.offsetTop;e = e.offsetParent;} return position;} getPos();") as ScriptObject;

            return position.ConvertTo<Point>();
        }
    }
}
